import React, { useEffect, useState, useImperativeHandle, forwardRef } from "react";
import Router, { withRouter } from '@/router/renderRouter';
import { deepclone, useSyncCallback } from "@/utils";
import { Table, message, Divider, Tag, Card, Select, Form, InputNumber, Input, Button, Radio, Spin, Popconfirm, Switch, Col, Row, DatePicker, Popover } from "antd";
import BreadcrumbBox from "@/components/Base/BreadcrumbBox";
import moment from 'moment';
import './index.scss'; 

import { 
  merchantList,
  merchantUpdateStatus,
  merchantClassList,
} from '@/api/api'
let milCToken = {}
let first = false

const ManageIndex = forwardRef((props, ref) => {
  const { route, history } = props
  const { RangePicker } = DatePicker;
  const [values] = useState({
    time: [moment(),moment()],
  })
  const [formData, setFormData] = useState(values)
  const [searchForm] = Form.useForm();
  const layout = { sm: 24, md: 12, lg: 12, xl: 7, xxl: 7 };
  const layoutbtn = { sm: 24, md: 24, lg: 24, xl: 4 };
  const labelCol = { sm: 24, md: 6, lg: 6, xl: 6 };
  const wrapperCol = { sm: 24, md: 18, lg: 18, xl: 18 };
  
  // 列表数据
  const [total, setTotal] = useState(0)
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([]);
  
  const [id, setId] = useState(null);
  const [info, setInfo] = useState(null); 
  const [merchantOptions, setMerchantOptions] = useState([]);
  // 状态
  const [statusShow, setStatusShow] = useState(false)
  const [statusIndex, setStatusIndex] = useState(null)
  
  // 面包屑
  const breadcrumbList = ['商户管理', '商户列表']
  
  // 表单头部
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      render: (text: any, row: any, index: number) => `${index + 1}`,
    },
    {
      title: '商户账号',
      dataIndex: 'userName',
      key: 'userName',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '商户编号',
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '商户名称',
      dataIndex: 'nickName',
      key: 'nickName',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '商户余额',
      dataIndex: 'merchantBalance',
      key: 'merchantBalance',
      align: 'center',
    },
    {
      title: '商户类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '商户分类',
      dataIndex: 'merchantClass',
      key: 'merchantClass',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '开户日期',
      dataIndex: 'registerEndDate',
      key: 'registerEndDate',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (text, row, index) => {
        return <>
          {
            <Popover
              placement="bottom"
              content={StatusBox(row, index)} 
              trigger="click" 
              visible={statusShow&&(statusIndex===index)}
              onVisibleChange={(visible) => {
              setStatusShow(visible)
              setStatusIndex(index)
            }}>
              <Tag color={text == 1 ? '#52c41a' : '#f5222d'}
                onClick={() => {setStatusShow(true)}}
              >
                {text == 1 ? '启用' : (text == 2 ? '停用' : '冻结资金')}
              </Tag>
            </Popover>
          }
        </>
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 300,
      fixed: 'right',
      render: (text: string, record: any) => {
        return <>
          <a onClick={() => {
            props.setParams({
              userId: record.id
            })
            props.setPageType('info')
          }}
          >修改</a>
          <Divider type="vertical" />
          <a onClick={() => {
            props.open({
              id: record.id,
              userName: record.userName,
              merchantCode: record.merchantCode,
            })
          }}
          >修改余额</a>
          <Divider type="vertical" />
          <a onClick={() => {
            props.setParams({
              userId: record.id,
              activeKey: '1',
              userName: record.userName,
            })
            props.setPageType('log')
          }}
          >登录日志</a>
          <Divider type="vertical" />
          <a onClick={() => {
            props.setParams({
              userId: record.id,
              activeKey: '2',
              userName: record.userName,
            })
            props.setPageType('log')
          }}
          >操作日志</a>
          <Divider type="vertical" />
          <a onClick={() => {
            props.setParams({
              userId: record.id,
              userName: record.userName,
            })
            props.setPageType('balanceHistory')
          }}
          >账变记录</a>
          <Divider type="vertical" />
          <a onClick={() => {
            props.setParams({
              userId: record.id,
              userName: record.userName,
            })
            props.setPageType('transferRecord')
          }}
          >转账记录</a>
        </>;
      },
    }
  ];
  
  // 获取商户分类
  const merchantClassListHanlder = async () => {
    try {
      let res = await merchantClassList()
      if(res.code === 0) {
        let arr = []
        res.data.forEach(item=>{
          arr.push({
            value: item.id,
            label: item.className,
          })
        })
        setMerchantOptions(arr)
      }
    } catch(error) {
      console.log(error)
    }
  }
  
  // 商户列表
  const handleFinish = async () => {
    try {
      let { time, type, status, merchantClassId, userName, nickName, merchantCode } = deepclone(formData);
      let params = {
        pageSize,
        currentPage,
        type,
        status,
        merchantClassId,
        userName,
        nickName,
        merchantCode,
        registerBeginDate: moment(time[0]).format('YYYY-MM-DD'),
        registerEndDate: moment(time[1]).format('YYYY-MM-DD'),
      }
      setLoading(true)
      let res = await merchantList(params)
      if(res.code === 0) {
        setDataSource(res.data.records || [])
        setTotal(res.data.total)
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  }
  
  // 搜索
  const onFinish = () => {
    setCurrentPage(1)
    setPageSize(20)
    searchData()
  }
  
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    handleFinish()
  })
  
  // 状态 content
  const StatusBox = (props, index) => {
    let [noticeStatus, setMerchantStatus] = useState(parseInt(props.status))
    // 改变状态
    const changeStatus = async (status) => {
      try {
        let res = await merchantUpdateStatus({
          status,
          merchantId : props.id
        })
        if(res.code === 0) {
          searchData()
        }
        setStatusShow(false)
        setStatusIndex(null)
        message.destroy()
        message.success('修改状态成功')
      } catch (error) {
        console.log(error)
      }
    }
    // 初始化
    useEffect(() => {
      if(parseInt(statusIndex) === index) {
        setMerchantStatus(props.status)
      }
      return () => {};
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [statusShow, statusIndex])
  
    return (
      <div className='status-box'>
        <div className='status-item radio'>
          <span>
            <Radio.Group onChange={(ev) => {
              setMerchantStatus(ev.target.value)
              changeStatus(ev.target.value)
            }} value={noticeStatus}>
              <Radio value={1}>启用</Radio>
              <Radio value={2}>停用</Radio>
              <Radio value={3}>冻结资金</Radio>
            </Radio.Group>
          </span>
        </div>
      </div>
    )
  }
  
  // 更新
  useEffect(() => {
    if(first) {
      searchData()
      merchantClassListHanlder()
    }
    return () => {};
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, pageSize])
  
  // 首次更新
  useEffect(() => {
    searchData()
    first = true
    return () => { 
      first = false
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  useImperativeHandle(ref, () => ({
    handleFinish,
  }))
  return (
    <>
      <div className="system-component">
        <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
        <div className="system-main">
          <Form initialValues={values} form={searchForm} onFinish={(val) => {
            setFormData(val)
            onFinish()
          }}>
            <Card>
              <Row>
                <Col {...layout}>
                  <Form.Item
                    label="开户时间"
                    name="time"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <RangePicker allowClear={false} />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="商户类型"
                    name="type"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select options={[
                      {value: '1', label: '现金'},
                      {value: '2', label: '信用'},
                    ]} />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="商户分类"
                    name="merchantClassId"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select options={merchantOptions} />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="商户状态"
                    name="status"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select options={[
                     {value: 1, label: '启用'},
                     {value: 2, label: '停用'},
                     {value: 3, label: '冻结资金'},
                    ]} />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="商户账号"
                    name="userName"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="商户编号"
                    name="merchantCode"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="商户名称"
                    name="nickName"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                
                <Col {...layoutbtn}>
                  <div className="button-left">
                    <Button type="primary" htmlType="submit">
                      搜索
                    </Button>
                    <Button className='reset-btn' type="default" htmlType="button" onClick={() => {
                      searchForm.resetFields()
                      setFormData(searchForm.getFieldsValue(true))
                      onFinish()
                    }}>
                      重置
                    </Button>
                  </div>
                </Col>
              </Row>
            </Card>
          </Form>
          <div className="table-box">
            <Card>
              <Table
                loading={loading}
                size='middle'
                bordered
                scroll={{ x: 1000 }}
                rowKey={'id'}
                className='antd-table'
                dataSource={dataSource}
                pagination={false}
                pagination={{
                  size: 'default',
                  current: currentPage,
                  total,
                  showSizeChanger: true,
                  pageSize: pageSize,
                  onChange: (page, pagesize) => {
                    setCurrentPage(page)
                    setPageSize(pagesize)
                  }
                }}
                columns={columns} />
            </Card>
          </div>
        </div>
      </div>
    </>
  )
})
export default ManageIndex